import {queryFakeList, removeFakeList, addFakeList, updateFakeList} from '@/services/api';
import * as oprationService from '../services/opration'
import * as routerRedux from "react-router-redux";
import {message} from "antd";
import * as categoryService from "../services/category";

export default {
  namespace: 'opration',
  state: {
    list: [],
    detail: {},
  },

  effects: {
    * fetch({payload}, {call, put}) {
      const response = yield call(oprationService.findAll, payload);
      yield put({
        type: 'queryList',
        payload: Array.isArray(response.data) ? response.data : [],
      });
    },
    * save({payload}, {call, put}) {
      const response = yield call(oprationService.save, payload);
      if (response.code == "SUCCESS") {
        message.success('新增成功');
        if(payload.type=="焦点图"){
          yield put(
            routerRedux.push({
              pathname: '/banner/list'
            })
          );
        }else if(payload.type=="广告位"){
          yield put(
            routerRedux.push({
              pathname: '/advert/list'
            })
          );
        }else if(payload.type=="user"){
          yield put(
            routerRedux.push({
              pathname: '/advert/list'
            })
          );
        }
      } else {
        alert(response.msg || "error_1")
      }
    },
    * detail({payload}, {call, put}) {
      const response = yield call(oprationService.detail, payload);
      yield put({
        type: 'queryDetail',
        payload: response.data ? response.data : {},
      });
    },
    * delete({payload}, {call, put}) {
      const response = yield call(oprationService.del, payload);
      message.success("删除成功")
      yield put({
        type: 'fetch',
        payload: {type:payload.type},
      });
    },
    * changeActiveState({payload}, {call, put}) {
      const response = yield call(oprationService.detail, payload);
      const changeStatueLoading = message.loading('修改文章状态中', 0);
      setTimeout(() => {
        changeStatueLoading();
      }, 5000);
      if (response.code == "SUCCESS") {
        changeStatueLoading();
        message.success("修改成功")
        yield put({
          type: 'fetch',
        });
      } else {
        changeStatueLoading();
        message.error(response.msg || "error_1")
      }
    },
    * submit({payload}, {call, put}) {
      let callback;
      if (payload.id) {
        callback = Object.keys(payload).length === 1 ? removeFakeList : updateFakeList;
      } else {
        callback = addFakeList;
      }
      const response = yield call(callback, payload); // post
      yield put({
        type: 'queryList',
        payload: response,
      });
    },
  },
  reducers: {
    queryList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    queryDetail(state, action) {
      return {
        ...state,
        detail: action.payload,
      };
    },
  }
};
